package com.wufeng.springcloud.controller;

import com.netflix.appinfo.InstanceInfo;
import com.wufeng.springcloud.entities.CommonResult;
import com.wufeng.springcloud.entities.Payment;
import com.wufeng.springcloud.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/payment")
public class PaymentController {

    @Value("${server.port}")
    private String port;

    @Resource
    private PaymentService paymentService;

    @Autowired
    private DiscoveryClient discoveryClient;

    @PostMapping(value = "/create")
    public CommonResult add(@RequestBody Payment payMent){
        return paymentService.create(payMent);
    }

    @GetMapping(value = "/list/{id}")
    public CommonResult list(@PathVariable("id") Long id){
        return paymentService.findById(id);
    }

    @GetMapping(value = "list")
    public CommonResult listAll(){
        return paymentService.findAll();
    }

    @PutMapping(value = "/update")
    public CommonResult update(@RequestBody Payment payment){
        return paymentService.update(payment);
    }

    @DeleteMapping(value = "/delete/{id}")
    public CommonResult update(@PathVariable Long id){
        return paymentService.delete(id);
    }

    @GetMapping("/discovery")
    public Object discovery(){
        List<String> list = discoveryClient.getServices();
        for(String str : list){
            log.info("service name : " + str);
        }
        List<ServiceInstance> instancesList =  discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        for(ServiceInstance serviceInstance : instancesList){
            log.info(serviceInstance.getInstanceId() + "\t" + serviceInstance.getHost() + "\t" + serviceInstance.getPort() + "\t" + serviceInstance.getUri());
        }
        return discoveryClient;
    }

    @GetMapping(value = "/lb")
    public String lb(){
        return port;
    }

    @GetMapping("/feign/timeout")
    public String paymentFeignTimeOut() {
        try {TimeUnit.SECONDS.sleep(3);} catch (InterruptedException e){e.printStackTrace();}
        return port;
    }
}
